package arpc

import (
	"context"
	"io"
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpc"
)

type ErrorResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type HttpClient struct {
	ctx    context.Context
	method string
	url    string
	req    any

	rawresp    *http.Response
	statusCode int
}

func NewHttpClient(ctx context.Context, method string, url string, req any) *HttpClient {
	return &HttpClient{
		ctx:    ctx,
		method: method,
		url:    url,
		req:    req,
	}
}

func (hc *HttpClient) Do() error {
	resp, err := httpc.Do(hc.ctx, hc.method, hc.url, hc.req)
	if err != nil {
		return err
	}

	hc.rawresp = resp
	hc.statusCode = resp.StatusCode

	return nil
}

func (hc *HttpClient) StatusCode() int {
	if hc.rawresp == nil {
		return 0
	}

	return hc.statusCode
}

func (hc *HttpClient) Body() ([]byte, error) {
	return io.ReadAll(hc.rawresp.Body)
}

func (hc *HttpClient) Parse(val any) error {
	return httpc.Parse(hc.rawresp, val)
}

func (hc *HttpClient) Close() {
	if hc.rawresp != nil {
		hc.rawresp.Body.Close()
	}
}
